import os
from pdf2image import convert_from_path


class PDFToImageConverter:
    def __init__(self, poppler_path=r"D:\software\poppler-25.07.0\Library\bin"):
        """
        初始化PDF转换器

        Args:
            poppler_path: poppler库路径，如果为None则使用系统路径
        """
        self.poppler_path = poppler_path

    def convert_pdf_to_images(self, pdf_path, output_dir=None, dpi=200, fmt="PNG"):
        """
        将PDF转换为图片

        Args:
            pdf_path: PDF文件路径
            output_dir: 输出目录，如果为None则使用PDF所在目录
            dpi: 图片分辨率
            fmt: 图片格式（PNG/JPEG等）

        Returns:
            list: 保存的图片路径列表
        """
        # 验证PDF文件是否存在
        if not os.path.exists(pdf_path):
            raise FileNotFoundError(f"PDF文件不存在: {pdf_path}")

        # 设置输出目录
        if output_dir is None:
            output_dir = os.path.dirname(pdf_path)

        # 创建输出目录（如果不存在）
        os.makedirs(output_dir, exist_ok=True)

        # 获取PDF文件名（不含扩展名）
        pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]

        try:
            # 转换PDF为图片
            print(f"正在转换PDF: {pdf_path}")
            pages = convert_from_path(
                pdf_path,
                dpi=dpi,
                poppler_path=self.poppler_path
            )

            saved_paths = []

            # 保存每一页
            for i, page in enumerate(pages, start=1):
                # 生成输出文件名
                output_filename = f"{pdf_name}_page_{i}.{fmt.lower()}"
                output_path = os.path.join(output_dir, output_filename)

                # 保存图片
                page.save(output_path, fmt)
                saved_paths.append(output_path)
                print(f"已保存第 {i} 页: {output_path}")

            print(f"转换完成！共转换 {len(pages)} 页")
            return saved_paths

        except Exception as e:
            print(f"转换失败: {str(e)}")
            raise

    def batch_convert(self, pdf_directory, output_dir=None, dpi=200, fmt="PNG"):
        """
        批量转换目录中的所有PDF文件

        Args:
            pdf_directory: PDF文件所在目录
            output_dir: 输出目录
            dpi: 图片分辨率
            fmt: 图片格式

        Returns:
            dict: 每个PDF文件的转换结果
        """
        if not os.path.exists(pdf_directory):
            raise FileNotFoundError(f"目录不存在: {pdf_directory}")

        results = {}

        # 查找目录中的所有PDF文件
        pdf_files = [f for f in os.listdir(pdf_directory)
                     if f.lower().endswith('.pdf')]

        print(f"找到 {len(pdf_files)} 个PDF文件")

        for pdf_file in pdf_files:
            pdf_path = os.path.join(pdf_directory, pdf_file)
            try:
                saved_paths = self.convert_pdf_to_images(
                    pdf_path, output_dir, dpi, fmt
                )
                results[pdf_file] = {
                    'status': 'success',
                    'saved_paths': saved_paths
                }
            except Exception as e:
                results[pdf_file] = {
                    'status': 'failed',
                    'error': str(e)
                }
                print(f"转换 {pdf_file} 失败: {str(e)}")

        return results

    def set_poppler_path(self, poppler_path):
        """
        设置poppler路径

        Args:
            poppler_path: poppler库路径
        """
        self.poppler_path = poppler_path


# 使用示例
if __name__ == "__main__":
    # 初始化转换器
    converter = PDFToImageConverter(
        poppler_path=r"D:\software\poppler-25.07.0\Library\bin"
    )

    # 转换单个PDF
    pdf_path = r"C:\Users\33720\Desktop\外来语辨析第三版第一次.pdf"
    output_dir = r"C:\Users\33720\Desktop\disan"

    try:
        saved_images = converter.convert_pdf_to_images(
            pdf_path=pdf_path,
            output_dir=output_dir,
            dpi=200,
            fmt="PNG"
        )
        print("转换完成的图片:", saved_images)

    except Exception as e:
        print(f"转换过程中出现错误: {e}")

    # 批量转换示例
    # pdf_directory = r"C:\Users\33720\Desktop\pdf_files"
    # results = converter.batch_convert(pdf_directory)
    # print("批量转换结果:", results)